package com.agh.portal.domain;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.EntityManager;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.TypedQuery;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;

@RooJavaBean
@RooToString
@RooJpaActiveRecord(finders = { "findPostsByStudent", "findPostsByAghGroup", "findPostsByAghGroupAndTitleLike" })
public class Post {

    @Size(max = 80)
    @NotEmpty
    private String title;

    @Size(max = 5000)
    @NotEmpty
    private String content;

    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(style = "M-")
    private Date postDate;

    @ManyToOne
    private AghGroup aghGroup;

    @ManyToOne
    @NotNull
    private Student student;

    @OneToMany(cascade = CascadeType.ALL, mappedBy="post")
    private Set<Reply> replies = new HashSet<Reply>();

	public String toString() {
        return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }
	
    public static List<Post> findAllPosts() {
        return entityManager().createQuery("SELECT o FROM Post o ORDER BY o.postDate desc", Post.class).getResultList();
    }
    
    public static List<Post> findPostEntries(int firstResult, int maxResults) {
        return entityManager().createQuery("SELECT o FROM Post o ORDER BY o.postDate desc", Post.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
    }
    
    public static TypedQuery<Post> findLatestPostsByStudent(Student student, Integer maxResults) {
        if (student == null) throw new IllegalArgumentException("The student argument is required");
        EntityManager em = Post.entityManager();
        TypedQuery<Post> q = em.createQuery("SELECT o FROM Post AS o WHERE o.student = :student ORDER BY o.postDate desc", Post.class);
        q.setParameter("student", student);
        if(maxResults != null){
        	q.setMaxResults(maxResults);
        }
        return q;
    }
  
}
